package org.fuys.coder.domain.auth.service.vertify.email.impl;

import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.fuys.coder.common.constants.RedisConstants;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.domain.auth.model.req.EmailSendReq;
import org.fuys.coder.domain.auth.model.res.AuthFailedEnum;
import org.fuys.coder.domain.auth.repository.ICaptchaRepository;
import org.fuys.coder.domain.auth.service.vertify.email.EmailCodeVerify;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.auth.service.vertify.email.impl
 * @className: EmailCodeVerifyImpl
 * @author: WangJing
 * @description: 邮箱验证码实现类
 * @date: 2024/6/18 20:37
 * @version: 1.0
 */
@Service
public class EmailCodeVerifyImpl implements EmailCodeVerify {

    @Resource
    private Producer producer;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private ICaptchaRepository captchaRepository;

    @Override
    public boolean verify(String email, String code) {
        return false;
    }

    @Override
    public boolean send(EmailSendReq req) {
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setFrom("3816618168@qq.com");
        mailMessage.setSubject("Fuys低代码");
        mailMessage.setTo(req.getEmail());
        mailMessage.setText(req.getDesc()+req.getMsg());
        javaMailSender.send(mailMessage);
        return true;
    }

    @Override
    public String getCode(String email) {
        StringBuilder stringBuilder=new StringBuilder();
        for(int i=0;i<6;i++){
            int code= (int) (Math.random() * 10);
            stringBuilder.append(code);
        }
        String redisKey=RedisConstants.REDIS_FIELD_EMAIL + email;
        final String value = stringBuilder.toString();
        captchaRepository.saveCaptcha(redisKey, value);
        return value;
    }

    @Override
    public void getImageCaptcha(HttpServletResponse httpServletResponse, String uuid) {
        try {
            if(ObjectUtils.isEmpty(uuid))throw new IllegalArgumentException("uuid不能为空 请检查前端是否出现问题");
            //强制响应结果不缓存
            httpServletResponse.setHeader("Cache-Control","no-store, no-cache");
            //设置响应类型为图片
            httpServletResponse.setContentType("image/jpeg");
            BufferedImage image=this.getCaptcha(uuid);
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            IOUtils.closeQuietly(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("图形验证码写入失败!");
        }
    }

    private BufferedImage getCaptcha(String uuid){
        //测试阶段 只需要code=1234即可
        String code=this.producer.createText();
        code="1234";
        String redisKey= RedisConstants.REDIS_FIELD_CAPTCHA+uuid;
        captchaRepository.saveCaptcha(redisKey,code);
        return producer.createImage(code);
    }

    @Override
    public int checkCaptcha(String uuid,String code){
        String redisKey= RedisConstants.REDIS_FIELD_CAPTCHA+uuid;
        final String value = captchaRepository.getCaptcha(redisKey);
        if(ObjectUtils.isEmpty(value)){
            return AuthFailedEnum.CAPTCHA_EXPIRED.getIndex();
        }else{
            if(value.equals(code)){
                captchaRepository.deleteCaptcha(redisKey);
                return -1;
            }else{
                return AuthFailedEnum.CAPTCHA_MISMATCH.getIndex();
            }
        }
    }

}
